package com.atguigu.seckill.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * json工具类
 *
 */
public class JsonUtil {

    private  static ObjectMapper objectMapper=new ObjectMapper();
    /**
     * 将对象转换成json
      */
    public static String object2JsonStr(Object object){
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
         * 将字符串转换为对象
         *
         * @param <T> 泛型
         */
        public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz) {
            try {
                return objectMapper.readValue(jsonStr.getBytes("UTF-8"), clazz);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
     }
     /**
      * 将json数据转换成pojo对象list
      * <p>Title: jsonToList</p>
      * <p>Description: </p>
      *
      * @param jsonStr
      * @param beanType
      * @return
      */
         public static <T> List<T> jsonToList(String jsonStr, Class<T> beanType) {
            JavaType javaType =
                objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = objectMapper.readValue(jsonStr, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
